from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
import json
from api.serializers import ComputerSerializer
from computer.models import Computer,Count_City_Com,Count_Room_Com


@api_view(['GET','POST'])
def get_data(request):
    if request.method == 'GET':
        coms = Computer.objects.all()
        serializer = ComputerSerializer(coms,many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        if request.data:
            serializer = ComputerSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data,status=status.HTTP_200_OK)

    return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET','PUT','DELETE'])
def con_data(request,cid):
    try:
        computer = Computer.objects.get(id=cid)
    except Computer.DoesNotExist:
        return Response(status = status.HTTP_404_NOT_FOUND)
    if request.method == 'GET':
        serializer = ComputerSerializer(computer)
        return  Response(serializer.data)
    elif request.method == 'PUT':
        serializer = ComputerSerializer(computer,data = request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data,status=status.HTTP_200_OK)
        return Response(serializer.errors,status =status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        computer.delete()
        return  Response(status=status.HTTP_204_NO_CONTENT)








